package com.defangit.production.orm;

import com.defangit.production.domain.*;
import laogen.hibernate.CommonService;
import laogen.lang.exception.ParameterNotValidException;

import java.time.LocalDateTime;
import java.util.List;

public class StockAlterationService extends CommonService<StockAlteration> {
    StockAlteration addAlteration(Manufacture manufacture, Store store, double quantity, int flag){
        if (manufacture==null) throw ParameterNotValidException.nullParameter("产品信息异常");
        if (store==null) throw ParameterNotValidException.nullParameter("仓库信息异常");
        StockAlteration stockAlteration = new StockAlteration();
        stockAlteration.setCreateTime(LocalDateTime.now());
        stockAlteration.setManufacture(manufacture).setQuantity(quantity).setFlag(flag);
        //to do stock finder
        update(stockAlteration);
        commitSession();
        return get(stockAlteration.getId()).orElseThrow(()->ParameterNotValidException.zeroIdOrEntityNonExist("库存变动信息异常"));
    }

    public Boolean addAlteration(List<StockAlteration> stockAlterations) {
        if (stockAlterations==null||stockAlterations.isEmpty()) return false;
        stockAlterations.forEach(stockAlteration -> {
            Stock stock = new StockService().findAll()
                    .storeId(stockAlteration.getStore().getId())
                    .manufactureId(stockAlteration.getManufacture().getId())
                    .unique().orElse(null);
            if (stock==null) {
                stock = new Stock().setManufacture(stockAlteration.getManufacture())
                        .setStore(stockAlteration.getStore())
                        .setQuantity(stockAlteration.getQuantity())
                        .setIntoNum(stockAlteration.getQuantity());
                getSession().save(stock);
            }
        });
        saveOrUpdate(stockAlterations);
        commitSession();
        return true;
    }
}
